package com.cndw.kungfu.ext;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import com.cndw.commons.encoder.Base64;

public class SerializeProcesser {

	/**
	 * 序列化对象为String字符串
	 * 
	 * @param o
	 *            Object
	 * @return String
	 * @throws Exception
	 */
	public static String writeObject(Object o) throws Exception {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(bos);
		oos.writeObject(o);
		oos.flush();
		oos.close();
		String object = Base64.encode(bos.toByteArray());
		bos.close();
		return object;
	}

	/**
	 * 反序列化字符串为对象
	 * 
	 * @param object
	 *            String
	 * @return
	 * @throws Exception
	 */
	public static Object readObject(String object) throws Exception {
		ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decode(object));
		ObjectInputStream ois = new ObjectInputStream(bis);
		Object o = ois.readObject();
		bis.close();
		ois.close();
		return o;
	}

	// 写入文件
	public static void write(Object o, String filename) {
		try {
			ObjectOutputStream w = new ObjectOutputStream(new FileOutputStream(filename));
			w.writeObject(o);
			w.flush();
			w.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	// 读取文件
	public static Object Reader(String file) {
		try {
			ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
			Object o = in.readObject();
			in.close();
			return o;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

}
